<template>
  <!-- 单词本 -->
  <div>
    <div class="unit-select common-select">
      <span>{{ $route.query.wordBank ? "选择年级:" : "选择单元:" }}</span>
      <el-select
        v-if="!$route.query.wordBank"
        v-model="value"
        @change="changeGetWord"
        clearable
        placeholder="请选择"
      >
        <el-option label="全部" :value="null"> </el-option>
        <el-option
          v-for="item in unitList"
          :key="item.unit_id"
          :label="item.unit_name"
          :value="item.unit_id"
        >
        </el-option>
      </el-select>
      <el-select
        v-if="$route.query.wordBank"
        v-model="value"
        @change="changeGradeGetWord"
        placeholder="请选择"
      >
        <!-- <el-option label="全部" :value="null"> </el-option> -->
        <el-option
          v-for="item in gradeList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-select
        style="margin-left:10px;"
        v-if="$route.query.wordBank&&this.groupList.length"
        v-model="groupId"
        @change="changeGroupId"
        placeholder="请选择"
      >
        <!-- <el-option label="全部" :value="null"> </el-option> -->
        <el-option
          v-for="item in groupList"
          :key="item.unit_id"
          :label="item.unit_name"
          :value="item.unit_id"
        >
        </el-option>
      </el-select>
      <span v-if="value">
        <el-button
          v-if="$route.query.wordBank"
          type="text"
          style="margin-right: 20px; float: right;"
          @click="removeWords"
          >{{ this.isSelect ? "移出单词本" : "选择单词" }}</el-button
        >
        <el-button
          v-else
          type="text"
          style="margin-right: 20px; float: right;"
          @click="removeWords"
          >{{ this.isSelect ? "添加到生词" : "选择单词" }}</el-button
        >
      </span>
    </div>
    <div class="common-table common-pagination">
      <!-- 单词库 -->
      <el-table
        v-if="$route.query.wordBank"
        ref="multipleTable"
        border
        stripe
        @selection-change="handleSelectionChange"
        :data="wordData.list"
        style="width: 100%"
      >
        <el-table-column
          v-if="this.isSelect"
          type="selection"
          label="全选"
          width="100"
          align="center"
        >
          <!-- <template slot="header">
            <div class="flex-space-be">
              <span>全选</span>
              <el-switch
                v-model="isSelect"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </div>
          </template> -->
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="100px"
          :index="indexMethod"
        >
        </el-table-column>
        <el-table-column prop="phonetic_american" label="音标">
          <template slot-scope="scope">
            <div
              class="play-click cell-box"
              @click="playAudio('audio' + scope.row.id)"
            >
              <span v-if="scope.row.phonetic_american"
                >[{{ scope.row.phonetic_american }}]</span
              >
              <span v-else>-</span>
            </div>
            <audio
              :ref="'audio' + scope.row.id"
              :src="baseURL + scope.row.american"
            ></audio>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="单词"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <div
              class="table-text word-box cell-box click"
              @click="playAudio('audio' + scope.row.id)"
            >
              <div class="" :class="wordNameShow ? 'hidden-none' : ''">
                {{ scope.row.name }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="paraphrase"
          label="词义"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <div :class="wordParapShow ? 'hidden-none' : ''">
              {{ scope.row.paraphrase }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 其他 -->
      <el-table
        v-else
        border
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        stripe
        :data="wordData.list"
        style="width: 100%"
      >
        <el-table-column
          v-if="this.isSelect"
          type="selection"
          label="全选"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="100px"
          :index="indexMethod"
        >
        </el-table-column>
        <el-table-column prop="name" label="音标">
          <template slot-scope="scope">
            <div
              class="play-click cell-box"
              @click="playAudio('audio' + scope.row.id)"
            >
              <span v-if="scope.row.phonetic">[{{ scope.row.phonetic }}]</span>
              <span v-else>-</span>
            </div>
            <audio
              :ref="'audio' + scope.row.id"
              :src="baseURL + scope.row.word_audio_vo_list[0].url"
            ></audio>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="单词"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <div
              class="table-text word-box cell-box click"
              @click="playAudio('audio' + scope.row.id)"
            >
              <div class="" :class="wordNameShow ? 'hidden-none' : ''">
                {{ scope.row.name }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="词义"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <div class="word-box cell-box">
              <span
                v-for="(item, index) in scope.row.word_paraphrase_list"
                :key="index"
                class="table-text mr10"
                :class="wordParapShow ? 'hidden-none' : ''"
              >
                <span>{{ item.word_sex }}</span>
                <span>{{ item.paraphrase }}</span>
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="showPagination"
        class="fr"
        background
        layout="prev, pager, next"
        :total="$route.query.wordBank ? wordData.total : wordData.total_num"
        @current-change="handleCurrentChange"
        hide-on-single-page
        :page-size="wordParams.pageSize"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import { wordByUnitIdForStrange } from "@/api/index";
import {
  groupUnit,
  getStudentWordList,
  getGradeList,
  deleteStudentWord,
  addToStrange,
} from "@/api/individuationRead.js";
const defaulData = {
  gradeId: null,
  pageNum: 1,
  pageSize: 15,
};
export default {
  data() {
    return {
      isSelect: false,
      multipleSelection: [],
      value: null,
      wordNameShow: false,
      wordParapShow: false,
      wordData: {
        total: 0,
        total_num: 0,
        list: [],
        total_page: 0,
      },
      isFixed: true,
      wordParams: {
        pageNum: 1,
        pageSize: 15,
      },
      wordsData: Object.assign({}, defaulData),
      showPagination: true,
      gradeList: [],
      bookData: null,
      groupList: [],
      groupId: null,
    };
  },
  props: {
    unitList: {
      type: Array,
      default: function() {
        return [];
      },
    },
    initValue: {
      type: Number,
      default: null,
    },
    checkedBookData: {
      tyep: Object,
    },
  },
  methods: {
    changeGroupId(e) {
      this.getStudentWordList(e);
    },
    async groupUnit(gradeId) {
      let res = await groupUnit(gradeId);
      this.groupList = res.data;
      if (res.code == 405 || !res.data) {
        this.wordData.list = [];
        this.wordData.total = 0;
        this.wordData.total_page = 0;
        this.groupList=[]
        return;
      }
      this.groupId = this.groupList[0].unit_id;
      this.getStudentWordList(this.groupList[0].unit_id);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async removeWords() {
      if (!this.isSelect) {
        this.isSelect = true;
        return;
      }
      const txt = this.$route.query.wordBank ? "移除" : "添加";
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "info",
          message: `请选择${txt}单词`,
        });
        return;
      }
      let data = this.multipleSelection.map((item) => item.id);
      this.$confirm(`此操作将${txt}选中单词, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(async () => {
          if (this.$route.query.wordBank) {
            await deleteStudentWord({ wordIdList: data, gradeId: this.value,groupId:this.groupId });
            this.getStudentWordList(this.groupId);
          } else {
            await addToStrange({ unitId: this.value, wordIdList: data });
            this.getStudentWordList(this.groupId);
            // this.getWordList();
          }
          this.isSelect = false;
          this.$message({
            type: "success",
            message: `${txt}成功!`,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消${txt}!`,
          });
        });

      // console.log(this.multipleSelection,"this.multipleSelection");
      // // await addStudentWord(data)
      // this.$message({
      //   type: 'success',
      //   message: '移除成功!'
      // });
    },
    async getStudentWordList(groupId) {
      let params = {
        pageSize: this.wordParams.pageSize,
        pageNum: this.wordParams.pageNum,
        gradeId: this.value || this.gradeList[0].id,
        groupId,
      };
      let res = await getStudentWordList(params);
      this.wordData.list = res.data.list;
      this.wordData.total = res.data.total_num;
      this.wordData.total_page = res.data.total_page;
    },
    async getGradeList() {
      let type = null;
      if (this.bookData.book_id == 585) type = 0;
      if (this.bookData.book_id == 586) type = 1;
      let { data } = await getGradeList({ type });
      this.gradeList = data;
      this.value = data[0].id;
      this.groupUnit(data[0].id);
    },
    playAudio(refName) {
      // this.$pauseAllAudio();
      if (this.$refs[refName]) {
        this.$refs[refName].play();
      }
    },
    wordNameShowChange(value) {
      this.wordNameShow = value;
    },

    renderHeader(h, { column }) {
      if (column.label === "单词" || column.label === "词义") {
        let html = [];
        let span = h(
          "span",
          {
            class: "text-red",
          },
          column.label
        );
        // "##44aff3"
        let swit = h("el-switch", {
          attrs: {
            type: "primary",
            size: "small",
            activeColor: "#4d96fb",
            inactiveColor: "#F2F2F2",
            value:
              column.label === "单词" ? this.wordNameShow : this.wordParapShow,
          },
          on: {
            change: (value) => {
              column.label === "单词"
                ? (this.wordNameShow = value)
                : (this.wordParapShow = value);
            },
          },
        });

        html.push([span, swit]);
        return h("div", { class: "flex-space-be" }, html);
      } else {
        return column.label;
      }
    },
    handleCurrentChange(value) {
      this.wordParams.pageNum = value;
      if (this.$route.query.wordBank) {
        this.getStudentWordList(this.groupId);
      } else {
        this.getWordList();
      }
    },
    indexMethod(index) {
      return (
        (this.wordParams.pageNum - 1) * this.wordParams.pageSize + index + 1
      );
    },
    changeGetWord() {
      this.showPagination = false;
      this.wordParams.pageNum = 1;
      this.$nextTick(() => {
        this.showPagination = true;
      });
      this.getWordList();
    },
    changeGradeGetWord() {
      this.showPagination = false;
      this.wordsData.pageNum = 1;
      this.$nextTick(() => {
        this.showPagination = true;
      });
      this.groupUnit(this.value);
      // this.getStudentWordList();
    },
    getWordList() {
      let params = {
        pageSize: this.wordParams.pageSize,
        pageNum: this.wordParams.pageNum,
      };
      let data = {
        book_id: this.checkedBookData.book_id,
        phonetic_category: this.$store.getters.isBritish,
        unit_id: this.value ? this.value : null,
      };
      wordByUnitIdForStrange(params, data).then((res) => {
        if (res.code == 200 && res.data) {
          this.wordData = res.data.word_vo;
        }
      });
    },
  },
  created() {
    this.bookData = JSON.parse(localStorage.getItem("bookData"));
    if (this.$route.query.wordBank){
       this.getGradeList();
    }else{
      this.changeGetWord()
    }
  },
  watch: {
    initValue: {
      handler() {
        if (this.$route.query.wordBank) return;
        this.value = this.initValue;
        this.getWordList();
      },
      // immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-table__header .el-table-column--selection .cell .el-checkbox:after {
  content: "全选";
  margin-left: 10px;
  color: #ffff;
}
</style>
